﻿#region  
//=====================================================
// 文件名: DefaultCalssObjectPool                
// 创建者: #AuthorName#                
// 创建时间: #CreateTime#              	
// Email: #AuthorEmail#               
// 描述: 当前脚本的功能              
// 修改者列表: 修改者名字以及修改功能      
// 版权所有: #Copyright#                 
//======================================================
#endregion 



using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace FrameWork.ObjectPool
{
    public class CalssObjectPool<T> where T : class, new()
    {
        protected Stack<T> m_Pool = new Stack<T>();
        protected int m_MaxCount = 0;
        protected int m_NoRecycleCount = 0;

        public CalssObjectPool(int _maxCount)
        {
            m_MaxCount = _maxCount;
            for (int i = 0; i < m_MaxCount; i++)
            {
                m_Pool.Push(new T());
            }
        }


        public T Spawn(bool _creatIdPoolEmpty)
        {
            T obj = null;
            if (m_Pool.Count > 0)
            {
                obj = m_Pool.Pop();
                m_NoRecycleCount++;
            }
            else
            {
                if (_creatIdPoolEmpty)
                {
                    obj = new T();
                    m_NoRecycleCount++;
                }
            }
            return obj;
        }


        public bool Recycle(T obj)
        {
            if (obj == null)
            {
                Debug.LogError("the object to be recaimd is empty!");
                return false;
            }
            m_NoRecycleCount--;
            if (m_Pool.Count >= m_MaxCount && m_MaxCount > 0)
            {
                return false;
            }
            m_Pool.Push(obj);
            return true;
        }
    }
}